package com.sunxueqi.common.util;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.sunxueqi.common.exception.CustomException;
import com.sunxueqi.framework.security.LoginUser;

import lombok.extern.slf4j.Slf4j;

/**
 * 安全服务工具类
 * @author Sun
 *
 */
@Slf4j
public class SecurityUtils {

	public static Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}
	
	/**
	 * 获取登录用户
	 */
	public static LoginUser getLoginUser() {
		try {
			return (LoginUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
		}
	}
	
	/**
	 * 获取登录用户账号
	 * @return
	 */
	public static String getUsername() {
		try {
			return getLoginUser().getUsername();
		} catch (Exception e) {
			throw new CustomException("获取用户账号异常", HttpStatus.UNAUTHORIZED);
		}
	}
	
	/**
	 * 获取登录用户id
	 * @return
	 */
	public static String getUserId() {
		try {
			return getLoginUser().getUser().getId();
		} catch (Exception e) {
			throw new CustomException("获取用户id异常", HttpStatus.UNAUTHORIZED);
		}
	}
	
    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
    
    public static void main(String[] args) {
		System.out.println(encryptPassword("123456"));
	}
}
